<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head th:replace="~{shared/header(Mytitle='构图')}"/>
<body class="min-h-screen bg-gray-100 font-sans">
    <nav th:replace="~{shared/nav}"/>
    <div th:replace="~{shared/modal}"/>
    <!-- 模态框 -->
    <div id="cdmodal" class="fixed top-0 left-0 w-full h-full bg-gray-900 bg-opacity-50 flex items-center justify-center z-40 hidden">
        <div class="bg-white p-6 rounded-lg shadow-md max-w-screen-md">
            <!-- 图片展示区域 -->
            <div id="imageDisplay" class="mx-auto">
                <!-- 在这里插入图片 -->
                <img id='finalImage'/>
            </div>
            <!-- 操作按钮 -->
            <div class="flex justify-end mt-4">
                <button class="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded-full mr-2" onclick="collect()">收藏</button>
                <button class="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded-full mr-2" onclick="downloadImage()">下载</button>
                <button onclick="hideCdModal()" class="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded-full">取消</button>
            </div>
        </div>
    </div>
    <div class="flex h-screen">
        <div id="total" class="flex-grow flex items-center justify-center  mr-32">
            <!-- 主要内容区域 -->
            <div class="flex-1">
                <div class="max-w-2xl mx-auto p-4">
                    <div class="bg-white p-6 rounded-lg shadow-md">
                        <div class="mb-4">
                            <div class="font-bold text-lg text-blue-600 mb-2">构图:</div>
                            <input id="inputField" type="text" class="border border-gray-300 p-2 rounded-md w-full mb-4" placeholder="请输入..." />
                            <button onclick="handleImageRequest()" class="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded-full">获取图片</button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <footer th:replace="~{shared/footer}"/>
    <input type="hidden" id="getTranslation" th:value="@{/model/translation}"/>
    <input type="hidden" id="collectImage" th:value="@{/image/collect}">
</body>
</html>
<script th:inline="javascript">
    // 模态框显示函数
    function showCdModal() {
        $('#cdmodal').removeClass('hidden');
    }
    // 模态框隐藏函数
    function hideCdModal() {
        $('#cdmodal').addClass('hidden');
    }

    function _arrayBufferToBase64( buffer ) {
        var binary = '';
        var bytes = new Uint8Array( buffer );
        var len = bytes.byteLength;
        for (var i = 0; i < len; i++) {
            binary += String.fromCharCode( bytes[ i ] );
        }
        return window.btoa( binary );
    }

    function downloadImage() {
        const ImageElement = $("#finalImage")
        const src = ImageElement.attr('src')
        const href = document.createElement('a')
        href.href = src
        href.download =  $('#inputField').val() + '.png'
        document.body.appendChild(href)
        href.click()
        document.body.removeChild(href)
    }

    function base64ToBlob(base64Data) {
        const byteCharacters = atob(base64Data);
        const byteArrays = [];

        for (let offset = 0; offset < byteCharacters.length; offset += 512) {
            const slice = byteCharacters.slice(offset, offset + 512);

            const byteNumbers = new Array(slice.length);
            for (let i = 0; i < slice.length; i++) {
                byteNumbers[i] = slice.charCodeAt(i);
            }

            const byteArray = new Uint8Array(byteNumbers);
            byteArrays.push(byteArray);
        }

        return new Blob(byteArrays, { type: 'image/png' }); // 以图片为例，根据实际情况修改类型
    }

    function collect() {
        const ImageElement = $("#finalImage")
        const src = ImageElement.attr('src')
        const base64 = src.split(',')[1]
        var formData = new FormData();
        var blobData = base64ToBlob(base64)
        formData.append('imageBlob', blobData, 'image.png');
        console.log(blobData)
        $.ajax({
            url: $('#collectImage').val(),
            method: 'post',
            data: formData,
            contentType: false,
            processData: false,
            success: function(response) {
                if(response.result) {
                    showModal('成功','收藏成功','success')
                }else {
                    showModal('错误','收藏失败')
                }
            },
            error: function() {
                showModal('错误','收藏失败')
            }
        });
    }
    // 处理图片请求
    async function handleImageRequest() {
        try {
            var ImageLink ;
            const form = new FormData()
            var prompt = $('#inputField').val()
            if (prompt !== "") {
                const response = await $.ajax({
                    url: $('#getTranslation').val(),
                    method: 'post',
                    data: {
                        usermessage: `请把下面这句话翻译成英文:${prompt}`,
                    }
                })

                prompt = response.modelContent;
                form.append('prompt', prompt)
                const fetchResponse = await fetch('https://clipdrop-api.co/text-to-image/v1', {
                    method: 'POST',
                    headers: {
                        'x-api-key': [[${apiKey}]],
                    },
                    body: form,
                })
                const remainingCredits = fetchResponse.headers.get('x-remaining-credits');
                console.log(`Remaining Credits: ${remainingCredits}`);
                const buffer = await fetchResponse.arrayBuffer();
                ImageLink = _arrayBufferToBase64(buffer);
                const imgElement = $("#finalImage");
                imgElement.on("load", function () {
                    // 显示模态框
                    showCdModal();
                });

                imgElement.attr("src", `data:image/jpeg;base64,${ImageLink}`);
                imgElement.attr("alt", '请求失败');
            }else{
                console.log("输入为空111")
                showModal('错误', '输入不能为空');
            }
        }catch (error) {
            console.log(error)
            showModal('错误','请求失败')
        }
    }
</script>